<template>
<!-- 首页点击tab进入商场 -->
  <div class="shop-category">
    <Banner :banners="indexBanners" v-if="indexBanners && indexBanners.length" />

    <div class="box_flex">
        <!-- 搜索 -->
        <van-search v-model="search" style="width: 82%;" placeholder="商品名/品牌/商品种类/关键字" />
        <!-- 筛选 -->
        <div class="select-wrap">
            <!-- <selectBoxNew @sort="onChangeSort" @range="onChangeRange" /> -->
            <span class="shop-category__filter-type" style="padding:10rpx 0rpx;" @click="showFilter = true">
                <span class="icon">&#xe876;</span> 筛选
            </span>
        </div>
    </div>
    <!-- 排序 -->
    <SelectSort @sort="onChangeSort" @range="onChangeRange" />
    <div class="goods-box">
        <div v-if="list.length > 0" class="good clearfix">
            <ProductListItem v-for="(product, index) in list"
                :key="index"
                :cover="product.list_cover || product.cover"
                :name="product.name"
                :tag="product.tag"
                :shop-name="product.shop_name"
                :keywords="product.keywords"
                :price="product.price"
                :display-price="product.display_price"
                :read-number="product.visitor || 0"
                :share-number="product.share_number || 0"
                @click="onClickProduct(product)">
            </ProductListItem>
        </div>
        <div v-else-if="!productList.req" class="mall-index__empty">
            暂无数据
        </div>
    </div>

    <BottomTab value="mall" />

    <!-- 过滤器 -->
    <div v-if="showFilter" class="popup-container filter-popup" @click="showFilter = false">
        <div class="popup popup--pos-right" @click.stop>
            <div class="filter-popup__title">价格区间</div>
            <div class="filter-popup__input-wrap">
                <input type="number" v-model="tempFilter.min" placeholder="最低价" class="filter-popup__input">
                <span class="filter-popup__line">&nbsp;——&nbsp;</span>
                <input type="number" v-model="tempFilter.max" placeholder="最高价" class="filter-popup__input">
            </div>
            <!-- <div class="filter-popup__title">{{category}}</div> -->
            <!-- <template v-if="category != '婚纱摄影'">
                <div v-for="(row, rowIndex) in categoryList" :key="rowIndex" class="filter-popup__row">
                    <div class="filter-popup__item-wrap">
                        <div v-if="row[0]" class="filter-popup__item" :class="{'filter-popup__item--active': row[0].id === tempFilter.categoryId}" @click="onClickCategory(row[0])">{{row[0].name}}</div>
                    </div>
                    <div class="filter-popup__item-wrap">
                        <div v-if="row[1]" class="filter-popup__item" :class="{'filter-popup__item--active': row[1].id === tempFilter.categoryId}" @click="onClickCategory(row[1])">{{row[1].name}}</div>
                    </div>
                    <div class="filter-popup__item-wrap">
                        <div v-if="row[2]" class="filter-popup__item" :class="{'filter-popup__item--active': row[2].id === tempFilter.categoryId}" @click="onClickCategory(row[2])">{{row[2].name}}</div>
                    </div>
                </div>
            </template>
            <template v-if="category != '婚纱摄影'">
                <div class="filter-popup__title">品牌</div>
                <div v-for="(row, rowIndex) in brand" :key="rowIndex" class="filter-popup__row">
                    <div class="filter-popup__item-wrap">
                        <div v-if="row[0]" class="filter-popup__item" :class="{'filter-popup__item--active': row[0].id === tempFilter.brand}" @click="onClickBrand(row[0])">{{row[0].name}}</div>
                    </div>
                    <div class="filter-popup__item-wrap">
                        <div v-if="row[1]" class="filter-popup__item" :class="{'filter-popup__item--active': row[1].id === tempFilter.brand}" @click="onClickBrand(row[1])">{{row[1].name}}</div>
                    </div>
                    <div class="filter-popup__item-wrap">
                        <div v-if="row[2]" class="filter-popup__item" :class="{'filter-popup__item--active': row[2].id === tempFilter.brand}" @click="onClickBrand(row[2])">{{row[2].name}}</div>
                    </div>
                </div>
            </template> -->
            <!-- 搜索商品，一级分类 显示一级分类、二级分类(一级和二级需联动) 和规格 -->
                <template v-if="search || category">
                    <!-- <input type="number" v-model="parentType" placeholder="测试" class="filter-popup__input"> -->
                    <template v-for="(item2,index2) in getTopAllCategory ">
                        <!-- 一级分类 -->
                        <template v-if="item2.field == 'first_category_id'">
                            <div class="filter-popup__title" :key="index2">{{item2.title}}</div>
                            <div class="filter-popup_params" :key="index2">
                                <template v-for="(row, rowIndex) in item2.data" >
                                    <div class="filter-popup_params_item" :key="rowIndex" :class="{'filter-popup__item--active': row.name === tempFilter.first_category_name}" @click="onClickfirst_category_id(row)">{{row.name}}</div>
                                </template>
                            </div>
                        </template>
                        <!-- 规格 -->
                        <template v-if="item2.field == 'category_id'">
                            <div class="filter-popup__title" :key="index2">{{item2.title}}</div>
                            <div class="filter-popup_params" :key="index2">
                                <template v-for="(row4, rowIndex4) in item2.data" >
                                    <template v-if="tempFilter.first_category_id == ''">
                                        <div class="filter-popup_params_item" :key="rowIndex4" :class="{'filter-popup__item--active': row4.name === tempFilter.SpecName}" @click="onClickCategory(row4)">{{row4.name}}</div>
                                    </template>
                                    <template v-else>
                                        <template v-if="row4.flag && tempFilter.first_category_id != ''">
                                            <div class="filter-popup_params_item" :key="rowIndex4" :class="{'filter-popup__item--active': row4.name === tempFilter.SpecName}" @click="onClickCategory(row4)">{{row4.name}}</div>
                                        </template>
                                        <!-- 不可选的 -->
                                        <template v-else>
                                            <div class="filter-popup_params_item" :key="rowIndex4" style="color:#999;background-color:#e0e0e0;" >{{row4.name}}</div>
                                        </template>
                                    </template>
                                    
                                </template>
                            </div>
                        </template>
                        
                    </template>
                </template>
                <!-- 品牌 -->
                <template v-if="category != '婚纱摄影'">
                    <div class="filter-popup__title">品牌</div>
                    <div class="filter-popup_params">
                        <template v-for="(item, itemIndex) in brand" >
                            <div class="filter-popup_params_item" :key="itemIndex" :class="{'filter-popup__item--active': item.name === tempFilter.brand}" @click="onClickBrand(item)">{{item.name}}</div>
                        </template>
                    </div>
                </template>
                <!-- <template v-if="category != '婚纱摄影'">
                    <div class="filter-popup__title">品牌</div>
                    <div v-for="(row, rowIndex) in brand" :key="rowIndex" class="filter-popup__row">
                        <div class="filter-popup__item-wrap">
                            <div v-if="row[0]" class="filter-popup__item" :class="{'filter-popup__item--active': row[0].id === tempFilter.brand}" @click="onClickBrand(row[0])">{{row[0].name}}</div>
                        </div>
                        <div class="filter-popup__item-wrap">
                            <div v-if="row[1]" class="filter-popup__item" :class="{'filter-popup__item--active': row[1].id === tempFilter.brand}" @click="onClickBrand(row[1])">{{row[1].name}}</div>
                        </div>
                        <div class="filter-popup__item-wrap">
                            <div v-if="row[2]" class="filter-popup__item" :class="{'filter-popup__item--active': row[2].id === tempFilter.brand}" @click="onClickBrand(row[2])">{{row[2].name}}</div>
                        </div>
                    </div>
                </template> -->
            
            <div class="filter-popup__btn">
                <div @click="onClickSelectReset" class="btn btn-mobile btn-normal btn-white-red red-border">重置</div>
                <div @click="onChangeRange" class="btn btn-mobile btn-normal btn-red">确定</div>
            </div>
        </div>
    </div>
    
    
  </div>
</template>

<script lang="ts">
import { api } from "@/lib/api";
import store from "@/store";
import Banner from "@/components/common/banner.vue";

import TabBox from '@/components/common/tabBox.vue';

import ProductListItem from '@/features/product/listItem.vue';
import SelectBox from '@/features/shop/selectBox.vue';

import selectBoxNew from '@/features/shop/selectBoxNew.vue';
import SelectSort from '@/features/shop/selectSort.vue';

import ListEmpty from "@/components/list/listEmpty.vue";
import { Component, Vue, Watch } from "vue-property-decorator";
import { Route } from "vue-router";
import { EMPTY_LIST, ROUTE_NAME } from "@/lib/constant";
import { WatchDelay } from "@/lib/utils";

Component.registerHooks(["beforeRouteEnter"]);

// 新增
interface TabItem {
    text: string;
    label?: string;
    wd: string;
    bg: string;
    callback: any;
    textAlign?: string;
}

@Component({
  name: "Shopcategory",
  components: {
    Banner,
    
    TabBox,
    ProductListItem,
    SelectBox,
    selectBoxNew,
    SelectSort,

    ListEmpty
    // BuyCar,
  }
})



export default class MallIndex extends Vue {
  
  public shopId: any = null;
  public title: any = '';
  public sortValue: any = '';
  public sortName: any = '';
  public search = '';
  // 分类
  public category: any = '';

  /** 是否显示filter */
    public showFilter = false;
    // 筛选
    // public filter: {
    //     min: string;
    //     max: string;
    //     category: number;
    //     brand: number | null;
    // } = {
    //     /** 最低价格，单位: 分 */
    //     min: '',
    //     /** 最高价格，单位: 分 */
    //     max: '',
    //     category: -1,
    //     brand: null,
    // };
    public tempFilter: {
        min: string;
        max: string;
        categoryId: number;
        brand: string;
        SpecName: string;
        first_category_id: string,
        first_category_name: string,
    } = {
        min: '',
        max: '',
        categoryId: -1,
        brand: '',
        SpecName: '',
        first_category_id: '',
        first_category_name:'',
    };

    // 顶级分类id
    public topCategoryId: any = '';
    // category_id  一级分类id
    public category_id: any = '';

    // 有一级分类是 通过id请求 一级分裂、二级分裂和品牌
    public get getTopAllCategory(){
        return store.state.good.topAllCategory;
    }
    // 获取一级分类下的规格
    public getFirstCategorySpec(){
        return store.dispatch('good/getFirstCategorySpec', {
            top_category_id: this.topCategoryId,
            first_category_id: this.tempFilter.first_category_id
        });
    }

    /** 用户基础信息 */
    public get userBasicInfo() {
        return store.state.user.basicInfo;
    }

  /** banner */
  public get indexBanners() {
    return store.state.shop.indexBanners;
  }

  public setCategory(){
    this.category = this.$route.query.type;
  }
  public settopCategoryId(){
    this.topCategoryId = this.$route.query.id;
  }

  /** 区间是否有效 */
    public get isScreenValid() {
        if (this.tempFilter.min && this.tempFilter.max) {
            const low = Number(this.tempFilter.min);
            const high = Number(this.tempFilter.max);
            return !isNaN(low) && !isNaN(high) && (high > low);
        }
        return true;
    }
    /** 价格区间 */
    public get screen() {
        return this.isScreenValid
            ? {
                min: this.tempFilter.min ? Number(this.tempFilter.min) * 100 : '',
                max: this.tempFilter.min ? Number(this.tempFilter.min) * 100 : '',
            }
            : null;
    }

    //   点击一级分类
    public onClickfirst_category_id(category: IdName){
        this.tempFilter.first_category_id = String(category.id);
        this.tempFilter.first_category_name = category.name;

        this.tempFilter.SpecName = '';
        // 获取一级分类下的规格
        this.getFirstCategorySpec();
    }
    /**
     * 点击类别  规格
     */
    public onClickCategory(category: IdName) {
        this.tempFilter.SpecName = category.name;
    }


    /**
     * 点击类别
     */
    // public onClickCategory(category: IdName) {
    //     this.tempFilter.categoryId = category.id;
    // }


    /** 二级类别信息 */
    public get categoryList() {
        const list = store.state.shop.category[this.category] || [];
        const result: IdName[][] = [];
        for (let i = 0, len = list.length; i < len; i = i + 3) {
            const row: IdName[] = [];
            if (list[i]) {
                row.push(list[i]);
            }
            if (list[i + 1]) {
                row.push(list[i + 1]);
            }
            if (list[i + 2]) {
                row.push(list[i + 2]);
            }
            result.push(row);
        }
        return result;
    }
    /** 品牌列表 */
    public get brand() {
        const list = store.state.good.brand[this.category] || [];
        // const result: IdName[][] = [];

        // for (let i = 0, len = list.length; i < len; i = i + 3) {
        //     const row: IdName[] = [];
        //     if (list[i]) {
        //         row.push(list[i]);
        //     }
        //     if (list[i + 1]) {
        //         row.push(list[i + 1]);
        //     }
        //     if (list[i + 2]) {
        //         row.push(list[i + 2]);
        //     }
        //     result.push(row);
        // }
        // return result;
        return list;
    }
    /**
     * 点击品牌
     */
    public onClickBrand(brand: IdName) {
        this.tempFilter.brand = brand.name;
    }
    /** 商品列表 */
    public get productList() {
        // ${brand}_${shopId}_${category}_${categoryId}_
        const key = `${this.tempFilter.brand}_${this.shopId}_${this.category}_${this.tempFilter.SpecName}_${this.sortValue}_${JSON.stringify(this.screen)}_${this.search}`;
        const wrap = store.state.good.productList;
        return wrap[key] || {
            list: [],
            loaded: false,
            req: false,
        };
    }
    /** 商品列表 */
    public get list() {
        const map = store.state.good.productMap;
        return this.productList.list.map((id) => map[id]);
    }

    @WatchDelay('search', 500)
    @Watch('search')
    public onSearch() {
        this.getProductList(true,true);
    }
    
    // 重置
    public onClickSelectReset() {
        // this.tempFilter.min = '';
        // this.tempFilter.max = '';
        this.tempFilter = {
            min: '',
            max: '',
            categoryId: -1,
            brand: '',
            SpecName: '',
            first_category_id: '',
            first_category_name:'',
        };
        this.search = '';
        this.sortValue = '';
        this.sortName = '';
    }

    /**
     * 更新排序
     */
    public onChangeSort(sort: any) {
        this.sortValue = sort.val;
        this.sortName = sort.name;
        this.getProductList(false,false);
    }

    /**
     * 更新价格范围
     */
    public onChangeRange(range: any) {
        // this.min = range.min;
        // this.max = range.max;
        this.getProductList(false,false);
        this.showFilter = false;
    }

    /**
     * 点击商品
     */
    public onClickProduct(product: Product.ListItem) {
        // if (product.type === 'package') {
        //     api.navigateTo({
        //         url: '/pages/pkg_detail/main',
        //         query: {
        //             pkg_id: product.id,
        //         },
        //     });
        // } else if (product.type === 'good') {
        //     api.navigateTo({
        //         url: '/pages/product_detail/main',
        //         query: {
        //             product_id: product.id,
        //         },
        //     });
        // }
        // api.navigateTo({
        //     url: '/pages/product_detail/main',
        //     query: {
        //         product_id: product.id,
        //     },
        // });
        api.push({
            name: ROUTE_NAME.PRODUCT_DETAIL,
            params: {
                productId: product.id + '',
            },
        });
    }
    /**
     * 获取商品列表      brand: this.filter.brand,品牌 
     */
    public getProductList(forceUpdate = false,switchState) {
        console.log('switchState:',switchState)
        return store.dispatch('good/getProductList', {
            // offset: this.list.length,
            // count: 10,
            // sort: this.sortValue,
            // screen: this.screen,
            // forceUpdate,
            // name: this.search,
            // category:this.category
            brand: this.tempFilter.brand,
            shopId: this.shopId,
            category: this.category,
            SpecName: this.tempFilter.SpecName,
            // categoryId: this.tempFilter.categoryId >= 0 ? this.tempFilter.categoryId : null,//this.category,
            offset: switchState?0:this.list.length,
            count: 10,
            sort: this.sortValue,
            screen: this.screen,
            name: this.search,
            forceUpdate,
        });
    }
    //获取品牌列表
    public getBrandList(){
        return store.dispatch('good/getBrand', {
            parent: this.category?this.category:''
        });
    } 


    public onReachBottom() {
        this.getProductList(false,false);
        this.getBrandList();
    }

//   public async beforeRouteEnter(to: Route, from: Route, next: any) {
//     const type = to.query.type;
//     store.commit("utils/startRequest");
//     await Promise.all([
//       store.dispatch("shop/getIndexBanners"),
//     ]);
//     store.dispatch('shop/getCart', {}),
//     store.dispatch('utils/getPageConfig'),
//     store.dispatch('good/getProductList', {
//         offset: 0,
//         count: 10,
//         sort: '',
//         screen: {
//             min: '',
//             max: '',
//         },
//         name: '',
//         category:type,
//         forceUpdate:true
//     });
//     // 获取品牌
//     store.dispatch('good/getBrand', {
//         parent: type,
//     });
//     // 获取顶级分类下筛选内容
//     store.dispatch('good/getTopAllCategory', {
//         top_category_id: to.query.id,
//     });
//     store.commit("utils/endRequest");
//     next();
//   }
    // public get type() {
    //     return this.$route.params.type;
    // }
    // public get categoryTopid(){
    //     return this.$router.query.id;
    // }
   // 
  public async beforeRouteEnter(to: Route, from: Route, next: any) {
    //   const shopId = to.params.shopId;
      const type = to.params.type;
      await Promise.all([
          store.dispatch('utils/getPageConfig'),
      ]);
      next();
  }
  // 
  async created() {
    // 赋值
    this.setCategory();
    this.settopCategoryId();

    store.commit("utils/startRequest");
    await Promise.all([
      store.dispatch("shop/getIndexBanners"),
    ]);
    store.dispatch('shop/getCart', {}),
    store.dispatch('utils/getPageConfig'),
    store.dispatch('good/getProductList', {
        offset: 0,
        count: 10,
        sort: '',
        screen: {
            min: '',
            max: '',
        },
        name: '',
        category:this.category,
        forceUpdate:true
    });
    // 获取品牌
    store.dispatch('good/getBrand', {
        parent: this.category,
    });
    // 获取顶级分类下筛选内容
    store.dispatch('good/getTopAllCategory', {
        top_category_id: this.topCategoryId,
    });
    store.commit("utils/endRequest");

    // 新增分享
    window.onShareAppMessage = (data) => {
        // return {
        //     title: this.shopDetail.name,
        //     imageUrl: '',
        //     path: `/pages/SHOP_PRODUCT/main?shop_id=${this.shopId}&referrer_id=${this.userBasicInfo.id}`,
        // };

        const url = this.$router.resolve({
            name: ROUTE_NAME.HOME_SHOP_CATEGORY,
            params: {
                // shopId: this.shopId,
            },
            query: {
                type: this.category,
                mode: 'bridal',
                categoryType: '分类展示',
                id: this.topCategoryId,
                referrer: this.userBasicInfo.id + '',
            },
        }).route.fullPath;

        return {
            title: '商城',
            imageUrl: '',
            // path: `/pages/index/main?referrer_id=${this.userBasicInfo.id}`,
            miniprogramPath: `/pages/main/index?type=share&targeturl=${encodeURIComponent(url)}`, // 如果需要分享原始小程序页面路由，可传递此参数
        };
    };
    
    window.addEventListener("reachbottom", this.onReachBottom);
  }
  // 强制更新
  mounted() {
    this.$nextTick(() => {
      this.$forceUpdate();
    });
  }
  public beforeDestroy() {
    window.removeEventListener("reachbottom", this.onReachBottom);
  }
}
</script>

<style lang="less">
@import "../../lib/style/mixins.less";

.shop-category {
  background-color: @color-white;

  
}

.box_flex{
    display: flex;
}

.shop-category {
    // padding-bottom: @height-tabbar;

    .tabbox {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        padding: 5px 14px;
        // margin-top: -10px;
        .tabbox_item{
            width: 20%;
            margin-bottom: 10rpx;
        }
        .tabbox_item_img{
            width: 100rpx;
            height: 100rpx;
            border-radius: 50%;
            margin: 15rpx auto;
        }
        .tabbox_item_title{
            width: 100%;
            text-align: center;
            font-size: 24rpx;
        }
        .bg-pink {
            background-color: #FFEDED;
            .icon {
                color: #fababd;
            }
        }
        .bg-blue {
            background-color: #E7F3FF;
            .icon {
                color: #9ec6fa;
            }
        }
    }

    .hot-recommend {
        padding: 10px 25px;
        .content {
            margin-right: -10px;
            .item {
                width: 156px;
                height: 88px;
                margin-top: 10px;
                margin-right: 10px;
                box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.4);
                border-radius: 10px;
                overflow: hidden;
                image {
                    width: 100%;
                    height: 100%;
                    border-radius: 10px;
                }
            }
        }
    }

    .select-wrap {
        padding-top: 36rpx;
    }

    .goods-box {
        padding: 0 18px 10px;
        .good {
            margin-right: -13px;
        }
    }

    &__empty {
        padding: 100px 0;
        .text-normal();
        color: @color-font-3;
        text-align: center;
    }
}

</style>
